// pages/product/product.js
import { Product } from 'product-model.js';
import { Cart } from '../cart/cart-model.js';
var product = new Product();// 实例化 商品详情 对象
var cart = new Cart();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: null,
    countArray: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    productCounts: 1,
    currentTabsIndex: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var id = options.id;
    this.data.id = id;
    this._loadData();
  },

  /**
   * 加载所有数据
   */
  _loadData: function () {
    product.getDetailInfo(this.data.id, (data) => {
      this.setData({
        cartTotalCounts: cart.getCartTotalCounts(),
        product: data
      });
    });
  },

  /**
   * 选择购买数目
   */
  bindPickerChange: function (event) {
    var index = event.detail.value;
    var selectdCount = this.data.countArray[index];
    this.setData({
      productCounts: selectdCount
    });
  },

  /**
   * 切换详情面板
   */
  onTabsItemTap: function (event) {
    var index = product.getDataSet(event, 'index');
    this.setData({
      currentTabsIndex: index
    });
  }

  , onAddingToCartTap: function (event) {
    this.addToCart();
    //var counts = this.cartTotalCounts + this.data.product.counts;

    this.setData({
      cartTotalCounts: cart.getCartTotalCounts()
    });
  }

  , addToCart: function () {
    var tempObj = {};
    var keys = ['id', 'name', 'main_img_url', 'price'];
    
    for (var key in this.data.product) {
      if(keys.indexOf(key) >= 0) {
        tempObj[key] = this.data.product[key];
      }
    }
    
    cart.add(tempObj, this.data.productCounts);
  },

  onCartTap: function (event) {
    wx.switchTab({
      url: '/pages/cart/cart'
    });
  }
})